|
|
|
|
|
Not always do you want to perform a sequential
set of statements. In order to control when the statements perform, control
structures are used. |
|
Conditional statement: |
|
if
else |
|
Selection statement: |
|
switch
|
|
Iterative statements: |
|
for, continue, break |
|
while and do
. While |
|
goto statement |
|
|
|
|
If a program has three parts, called Start, Middle,
and End, the flow of control could look like: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
case i of |
|
1: write(one); |
|
2: write(two); |
|
3: write(three); |
|
4: begin |
|
write(four); |
|
i := 3 |
|
end |
|
otherwise |
|
write(Bad value) |
|
end; |
|
|
|
|
case i of |
|
0: write(ZeroOne); |
|
1: write(One) |
|
end; |
|
|
|
|
|
|
|
|
|
|
while x < y do |
|
x := 2 * x |
|
|
|
|
|
|
|
|
|
|
|
for i := 1 to n do |
|
x[i] := 0 |
|
|
|
|
|
|
|
C provides two commands to control how we loop: |
|
break -- exit form loop or switch. |
|
continue -- skip 1 iteration of loop. |
|
|
|
|
|
|
if, while, repeat, for, or case |
|
begin |
|
|
|
|
|
goto 1 |
|
|
|
end; |
|
1: |
|
|
|
|
while,
repeat, or for |
|
begin |
|
|
|
|
|
goto 1 |
|
|
|
1: |
|
end; |
|
|
|
|
procedure p
|
|
. |
|
goto 1; |
|
|
|
1: |
|
end |
|
|
|
|
function f
|
|
. |
|
f := somevalue; |
|
goto
1; |
|
|
|
1: |
|
end |
|
|
|
|
|
goto statement unconditionally transfers control
to the statement with the given label. |
|
A label is an identifier followed by a colon: |
|
|
|
goto label; |
|
label: do something; |
|
|
|
|
|
|
Use = for assignment, == for comparisons |
|
Logical && and || are short circuits |
|
Use break to implement multiple exits from loops |
|
For each case in a switch statement, there
should be a break statement unless required otherwise. |
|